package logic

import (
	"context"
	"doctor-medicine-system/mysql"
	"errors"
	"gorm.io/gorm"

	"doctor-medicine-system/doctorrpc/doctorrpc"
	"doctor-medicine-system/doctorrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type MedicineUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewMedicineUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MedicineUpdateLogic {
	return &MedicineUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 药品修改
func (l *MedicineUpdateLogic) MedicineUpdate(in *doctorrpc.MedicineUpdateRequest) (*doctorrpc.MedicineUpdateResponse, error) {
	// todo: add your logic here and delete this line

	var doctor mysql.Doctor
	err := doctor.FindDoctor(mysql.DB, in.DoctorId)
	if err != nil {
		return nil, errors.New("医生不存在")
	}
	if doctor.Address != "内科" {
		return nil, errors.New("该医生无权限修改")
	}
	var medicine mysql.Medicine
	err = medicine.MedicineFind(mysql.DB, in.MedicineId)
	if err != nil {
		return nil, errors.New("药品不存在")
	}
	medicine = mysql.Medicine{
		Model:        gorm.Model{ID: uint(in.MedicineId)},
		MedicineName: in.MedicineName,
		Size:         in.Size,
		Where:        in.Where,
		Methods:      in.Methods,
		BadMethods:   in.BadMethods,
	}
	err = medicine.MedicineUpdate(mysql.DB)
	if err != nil {
		return nil, errors.New("修改失败")
	}
	return &doctorrpc.MedicineUpdateResponse{
		MedicineId: int64(medicine.ID),
	}, nil
}
